<?php

namespace app\common\model;

use Overtrue\EasySms\EasySms;

class Sms
{
    private $config = null;
    private $error = '';

    public function __construct()
    {
        $this->config = [
            // HTTP 请求的超时时间（秒）
            'timeout' => 5.0,

            // 默认发送配置
            'default' => [
                // 网关调用策略，默认：顺序调用
                'strategy' => \Overtrue\EasySms\Strategies\OrderStrategy::class,

                // 默认可用的发送网关
                'gateways' => [
                    'aliyun',
                ],
            ],
            // 可用的网关配置
            'gateways' => [
                'errorlog' => [
                    'file' => root_path() . 'runtime/sms/' . date('Ymd') . '/easy-sms.log',
                ],
                'aliyun' => [
                    'access_key_id' => env('aliyun_sms.access_key_id'),
                    'access_key_secret' => env('aliyun_sms.access_key_secret'),
                    'sign_name' => '有美惠充',
                ],
            ],
        ];
    }

    /**
     * 阿里云短信发送平台
     */
    public function send($mobiles, $params)
    {
        $easySms = new EasySms($this->config);

        $result = [];
        $status = 3;
        foreach ($mobiles as $mobile) {
            try {
                $res = $easySms->send($mobile, $params);
                $result[$mobile] = $res;
                $status = 2;
            } catch (\Overtrue\EasySms\Exceptions\NoGatewayAvailableException $e) {
                $result[$mobile] = $e->getException('aliyun')->getMessage();
            } catch (\Exception $e) {
                $result[$mobile] = $e->getMessage();
            }
        }
        return compact('result', 'status');
    }

    public function getError()
    {
        return $this->error;
    }

    /**
     * 傲众短信发送平台
     */
    public function sendSms($mobile, $content)
    {
        $url = "http://www.aozhongyun.com/Admin/index.php/Message/send";
        $post = [
            'uid' => '10310',
            'pwd' => 'hPb4vQby',
            'mobile' => $mobile,
            'content' => $content
        ];
        $jsonPost = json_encode($post, true);
        $return = curlPost($url, $jsonPost);
        return json_decode($return, true);
    }
}
